package org.zdp.demo.config.okhttp.interceptor;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

@RequiredArgsConstructor
@Slf4j
public class RetryInterceptor implements Interceptor {

    public final int maxRetryCount;

    private int count = 0;

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) {
        try {
            return this.retry(chain);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Response retry(Chain chain) throws IOException {
        Response response = null;
        Request request = chain.request();
        IOException ex = null;
        try {
            response = chain.proceed(request);
            while (!response.isSuccessful() && count < maxRetryCount) {
                count++;
                retry(chain);
            }

            // 连接异常
        } catch (IOException e) {
            while (count < maxRetryCount) {
                count++;
                response = retry(chain);
            }
            ex = e;
        }

        if (null != ex) {
            throw ex;
        }

        return response;
    }
}
